<?php
// 应用公共文件

use think\helper\Str;

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed 返回结果
     * @author 牧羊人
     * @date 2020-04-21
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }

}

if (!function_exists('curl_request')) {

    /**
     * curl请求(支持get和post)
     * @param $url 请求地址
     * @param array $data 请求参数
     * @param string $type 请求类型(默认：post)
     * @param bool $https 是否https请求true或false
     * @return bool|string 返回请求结果
     * @author 贾二小
     * @since 2021/7/29
     */
    function curl_request($url, $data = [], $type = 'post', $https = false)
    {
        // 初始化
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        // 设置超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        // 是否要求返回数据
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($https) {
            // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            // 从证书中检查SSL加密算法是否存在
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        if (strtolower($type) == 'post') {
            // 设置post方式提交
            curl_setopt($ch, CURLOPT_POST, true);
            // 提交的数据
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        } elseif (!empty($data) && is_array($data)) {
            // get网络请求
            $url = $url . '?' . http_build_query($data);
        }
        // 设置抓取的url
        curl_setopt($ch, CURLOPT_URL, $url);
        // 执行命令
        $result = curl_exec($ch);
        if ($result === false) {
            return false;
        }
        // 关闭URL请求(释放句柄)
        curl_close($ch);
        return $result;
    }
}

if (!function_exists('datetime')) {

    /**
     * 时间戳转日期格式
     * @param int $time 时间戳
     * @param string $format 转换格式(默认：Y-m-d h:i:s)
     * @return false|string 返回结果
     * @author 贾二小
     * @since 2021/7/29
     */
    function datetime($time = 0, $format = 'Y-m-d H:i:s')
    {
        if (empty($time)) {
            $time = time();
        }
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }

}

if (!function_exists('export_excel')) {

    /**
     * 数据导出Excel(csv文件)
     * @param string $file_name 文件名称
     * @param array $tile 标题
     * @param array $data 数据源
     * @author 牧羊人
     * @date 2020-04-21
     */
    function export_excel($file_name, $tile = [], $data = [])
    {
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $file_name);
        $fp = fopen('php://output', 'w');
        // 转码 防止乱码(比如微信昵称)
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
        fputcsv($fp, $tile);
        $index = 0;
        foreach ($data as $item) {
            if ($index == 1000) {
                $index = 0;
                ob_flush();
                flush();
            }
            $index++;
            fputcsv($fp, $item);
        }
        ob_flush();
        flush();
        ob_end_clean();
    }
}

if (!function_exists('get_guid')) {

    /**
     * 获取唯一性GUID
     * @return string 返回结果
     * @author 贾二小
     * @since 2021/7/29
     */
    function get_guid()
    {
        $data = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // set version to 0100
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
}

if (!function_exists('get_server_ip')) {

    /**
     * 获取服务端IP地址
     * @return string 返回IP地址
     * @author 贾二小
     * @since 2021/7/29
     */
    function get_server_ip()
    {
        if (isset($_SERVER)) {
            if ($_SERVER['SERVER_ADDR']) {
                $server_ip = $_SERVER['SERVER_ADDR'];
            } else {
                $server_ip = $_SERVER['LOCAL_ADDR'];
            }
        } else {
            $server_ip = getenv('SERVER_ADDR');
        }
        return $server_ip;
    }
}

if (!function_exists('get_client_ip')) {

    /**
     * 获取客户端IP地址
     * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param bool $adv 否进行高级模式获取（有可能被伪装）
     * @return mixed 返回IP
     * @author 贾二小
     * @since 2021/7/29
     */
    function get_client_ip($type = 0, $adv = false)
    {
        $type = $type ? 1 : 0;
        static $ip = null;
        if ($ip !== null) {
            return $ip[$type];
        }
        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) {
                    unset($arr[$pos]);
                }
                $ip = trim($arr[0]);
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

}

if (!function_exists('get_zodiac_sign')) {

    /**
     * 根据月、日获取星座
     * @param unknown $month 月
     * @param unknown $day 日
     * @author 贾二小
     * @since 2021/7/29
     */
    function get_zodiac_sign($month, $day)
    {
        // 检查参数有效性
        if ($month < 1 || $month > 12 || $day < 1 || $day > 31) {
            return false;
        }

        // 星座名称以及开始日期
        $signs = array(
            array("20" => "水瓶座"),
            array("19" => "双鱼座"),
            array("21" => "白羊座"),
            array("20" => "金牛座"),
            array("21" => "双子座"),
            array("22" => "巨蟹座"),
            array("23" => "狮子座"),
            array("23" => "处女座"),
            array("23" => "天秤座"),
            array("24" => "天蝎座"),
            array("22" => "射手座"),
            array("22" => "摩羯座")
        );
        list($sign_start, $sign_name) = each($signs[(int)$month - 1]);
        if ($day < $sign_start) {
            list($sign_start, $sign_name) = each($signs[($month - 2 < 0) ? $month = 11 : $month -= 2]);
        }
        return $sign_name;
    }

}

if (!function_exists('get_format_time')) {

    /**
     * 获取格式化显示时间
     * @author 贾二小
     * @since 2021/7/29
     */
    function get_format_time($time)
    {
        $time = (int)substr($time, 0, 10);
        $int = time() - $time;
        $str = '';
        if ($int <= 2) {
            $str = sprintf('刚刚', $int);
        } elseif ($int < 60) {
            $str = sprintf('%d秒前', $int);
        } elseif ($int < 3600) {
            $str = sprintf('%d分钟前', floor($int / 60));
        } elseif ($int < 86400) {
            $str = sprintf('%d小时前', floor($int / 3600));
        } elseif ($int < 1728000) {
            $str = sprintf('%d天前', floor($int / 86400));
        } else {
            $str = date('Y年m月d日', $time);
        }
        return $str;
    }

}

if (!function_exists('get_tree')) {
    /**
     * 将数据格式化成树形结构
     * @param $data
     * @param $pId
     * @return array
     * @author 贾二小
     * @since 2021/4/12
     */
    function get_tree($data, $pId)
    {
        $tree = [];
        foreach($data as $k => $v)
        {
            if($v['pid'] == $pId) {
                $v['children'] = get_tree($data, $v['id']);
                $tree[] = $v;
                unset($data[$k]);
            }
        }
        return $tree;
    }
}

if (!function_exists('_current_user')) {

    /**
     * 获取当前登录用户信息
     * @param null $field
     * @return mixed|null
     * @author 贾二小
     * @since 2021/5/31
     */
    function _current_user($field = null)
    {
        $user_id = session('userId');
        if (!$user_id) {
            return null;
        }
        if ($field) {
            if ($field == 'id') {
                return $user_id;
            } else {
                $user = cache('user_' . $user_id);
                return isset($user[$field]) ? $user[$field] : null;
            }
        }
        return cache('user_' . $user_id);
    }
}

if (!function_exists('get_user_id_name')) {

    /**
     * 获取所有用户ID和姓名
     * @return mixed|object|\think\App
     * @author 贾二小
     * @since 2021/6/27
     */
    function get_user_id_name()
    {
        $user_data = cache('user_data');
        if(empty($user_data)){
            //获取所以用户ID和姓名
            $user_data = \think\facade\Db::name('user')
                ->where(['is_delete'=>0])
                ->column('name', 'id');
        }
        return $user_data;
    }
}

if (!function_exists('user_id_name')) {

    /**
     * 根据用户ID绑定用户名
     * @param $data
     * @param string $id_field
     * @param string $name_field
     * @author 贾二小
     * @since 2021/6/27
     */
    function user_id_name($data, $user_field)
    {
        $user_id_name = get_user_id_name();
        return array_map(
            function ($item) use ($user_field, $user_id_name) {
                foreach ($user_field as $vo){
                    $item[$vo['name']] = empty($item[$vo['id']]) ? '': $user_id_name[$item[$vo['id']]];
                }
                return $item;
            }, $data
        );
    }
}

if (!function_exists('get_config')) {

    /**
     * 获取配置参数
     * @author 贾二小
     * @since 2021/7/4
     */
    function get_config($code)
    {
        $config_data = cache('config_data');
        if(empty($config_data)){
            $config_data = \think\facade\Db::name('config')
                ->where(['status'=>0,'is_delete'=>0])
                ->column('value','code');
            cache('config_data',$config_data);
        }
        return $config_data[$code];
    }
}

if (!function_exists('get_basic_tree')) {

    /**
     * 获取字典类型和字典数据
     * @author 贾二小
     * @since 2021/7/31
     */
    function get_basic_tree(){
        $basic_tree_data = cache('basic_tree_data');
        if(empty($basic_tree_data)){
            $typeData = \think\facade\Db::query('select id,name,code from `sys_dict_type` where status = 0 and is_delete = 0 order by sort');
            $valueData = \think\facade\Db::query('select id,type_id,value,code from `sys_dict_data` where status = 0 and is_delete = 0 order by sort');
            //数据拼装
            $basic_tree_data = array_map(function ($item) use ($valueData){
                $item['id'] = strval($item['id']);
                $item['pid'] = '0   ';
                $item['children'] = [];
                foreach ($valueData as $key=>$vo){
                    if($item['id'] == $vo['type_id']){
                        $item['children'][] = [
                            'id'=>strval($vo['id']),
                            'pid'=>strval($vo['type_id']),
                            'code'=>$vo['code'],
                            'name'=>$vo['value'],
                            'children'=>[]
                        ];
                        unset($valueData[$key]);
                    }
                }
                return $item;
            }, $typeData);
            cache('basic_tree_data',$basic_tree_data);
        }
        return $basic_tree_data;
    }
}

if (!function_exists('to_camel')) {

    /**
     * 下划线转驼峰(首字母小写)
     * @author 贾二小
     * @since 2021/7/4
     */
    function to_camel($item){
        return array_combine(array_map(function ($key){return Str::camel($key);}, array_keys($item)),$item);
    };
}

if (!function_exists('to_snake')) {

    /**
     * 驼峰转下划线
     * @author 贾二小
     * @since 2021/7/4
     */
    function to_snake($item){
        return array_combine(array_map(function ($key){return Str::snake($key);}, array_keys($item)),$item);
    };
}

if (!function_exists('to_camel_array')) {

    /**
     * 数组下划线转驼峰(首字母小写)
     * @author 贾二小
     * @since 2021/7/26
     */
    function to_camel_array($data)
    {
        return array_map(function ($item) {return to_camel($item);}, $data);
    }
}

if (!function_exists('to_snake_array')) {

    /**
     * 数组驼峰转下划线
     * @author 贾二小
     * @since 2021/7/26
     */
    function to_snake_array($data)
    {
        return array_map(function ($item) {return to_snake($item);}, $data);
    }
}

if (!function_exists('format_file_size')) {

    /**
     * 文件大小格式化显示
     * @author 贾二小
     * @since 2021/8/12
     */
    function format_file_size($num): string
    {
        $p = 0;
        $format = 'bytes';
        if( $num > 0 && $num < 1024 ) {
            $p = 0;
            return number_format($num) . ' ' . $format;
        }
        if( $num >= 1024 && $num < pow(1024, 2) ){
            $p = 1;
            $format = 'KB';
        }
        if ( $num >= pow(1024, 2) && $num < pow(1024, 3) ) {
            $p = 2;
            $format = 'MB';
        }
        if ( $num >= pow(1024, 3) && $num < pow(1024, 4) ) {
            $p = 3;
            $format = 'GB';
        }
        if ( $num >= pow(1024, 4) && $num < pow(1024, 5) ) {
            $p = 3;
            $format = 'TB';
        }
        $num /= pow(1024, $p);
        return number_format($num, 3) . ' ' . $format;
    }

}